package com.example.demo.exception;


import com.example.demo.error.BusinessException;
import com.example.demo.error.EmBusinessError;
import com.example.demo.response.CommonReturnType;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class ExceptionHandler {

  @Autowired
  ObjectMapper om;

  @org.springframework.web.bind.annotation.ExceptionHandler(value = Exception.class)
  public CommonReturnType errorHandler(HttpServletRequest request, HttpServletResponse response, Exception ex) {
    ResponseStatus status = ex.getClass().getDeclaredAnnotation(ResponseStatus.class);
    if (status != null) {
      response.setStatus(status.value().value());
    } else {
      ex.printStackTrace();
      //发送报警邮件
      //...
    }

    CommonReturnType commonReturnType = new CommonReturnType();
    if (ex instanceof BusinessException) {
      BusinessException businessException = (BusinessException) ex;
      commonReturnType.setCode(businessException.getErrCode());
      commonReturnType.setMessage(businessException.getErrMsg());
    } else {
      commonReturnType.setCode(EmBusinessError.UNKNOW_ERROR.getErrCode());
      commonReturnType.setMessage(EmBusinessError.UNKNOW_ERROR.getErrMsg());
    }

    return commonReturnType;
  }

  // 获取header对象
  private String getHeadersInfo(HttpServletRequest request) throws JsonProcessingException {
    Map<String, String> map = new HashMap<>();
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
      String key = (String) headerNames.nextElement();
      String value = request.getHeader(key);
      map.put(key, value);
    }
    return om.writeValueAsString(map);
  }


}
